﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using OpenCLNet;
using Image = OpenCLNet.Image;

namespace GPUTracer
{
    public static class ImageLoader
    {
        private static readonly Dictionary<string, OpenCLNet.Image> _filenameToImageMap = new Dictionary<string, Image>();
        public static Context OclContext { get; set; }

        public static OpenCLNet.Image LoadImage(string file)
        {
            if (_filenameToImageMap.ContainsKey(file))
                return _filenameToImageMap[file];

            OpenCLNet.Image im;
            try
            {
                im = CreateOCLBitmapFromBitmap(new Bitmap(file));
            }
            catch (Exception ex)
            {
                return null;
            }

            _filenameToImageMap.Add(file, im);
            return im;
        }

        private static OpenCLNet.Image CreateOCLBitmapFromBitmap(Bitmap bitmap)
        {
            BitmapData bd = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
            Image oclImage = OclContext.CreateImage2D((MemFlags)((long)MemFlags.READ_ONLY | (long)MemFlags.COPY_HOST_PTR),
                                                      OpenCLNet.ImageFormat.RGBA8U, bd.Width, bd.Height, bd.Stride, bd.Scan0);
            bitmap.UnlockBits(bd);
            return oclImage;
        }
    }
}
